package com.baizhi.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    private static final Logger log = LoggerFactory.getLogger(DemoController.class);

    // 作用：代表这是一个sentinel资源
    // value：资源别名   blockHandler：使用sentinel进行不同规则控制时的默认处理方案   fallback：自定义业务出错时默认处理方案   defaultFallback：指定一个业务错误时默认方案
    @SentinelResource(value = "aaa", blockHandler = "blockHandler", fallback = "fallback", defaultFallback = "defaultFall")
    @GetMapping("/demo")
    public String demo(Integer id) {
        log.info("demo ok ...");
        if (id < 0) {
            throw new RuntimeException("id无效");
        }
        return "demo ok !!!";
    }

    // 使用sentinel进行不同规则控制时的默认处理方案
    public String blockHandler(Integer id, BlockException e) {
        if (e instanceof FlowException) {   // 流控异常
            return "当前请求过于火爆，您已被流控！！！";
        } else if (e instanceof DegradeException) {     // 降级异常
            return "当前请求过于火爆，您已被降级！！！";
        } else if (e instanceof ParamFlowException) {   // 热点参数异常
            return "当前请求过于火爆，您已被热点参数限流！！！";
        }
        return "服务器快爆了，请稍后重试！！！";
    }

    // 自定义业务出错时默认处理方案
    public String fallback(Integer id) {
        return "服务器出错啦！！！";
    }

    // 指定一个业务错误时默认方案
    public String defaultFall(Integer id) {
        return "自定义服务器出错啦！！！";
    }

    @GetMapping("/test")
    public String test() {
        log.info("test ok ...");
        return "test ok !!!";
    }
}
